import {createSlice} from "@reduxjs/toolkit";
import {http} from "@/utils/request";
import {clearToken, getToken, setToken as _setToken} from "@/utils/token";
import {getProfileAPI, loginAPI} from "@/apis/user";


const userStore = createSlice({
    name: 'user',
    initialState: {
        token: getToken() || '',
        userInfo: {}
    },
    reducers: {
        setToken(state, action) {
            state.token = action.payload
            _setToken(state.token)
        },
        setUserInfo (state, action) {
            state.userInfo = action.payload
        },
        clearUserInfo(state) {
            state.token = ''
            state.userInfo = {}
            clearToken()
        },
    }
})

const {setToken,setUserInfo,clearUserInfo} = userStore.actions

const userReducer = userStore.reducer

/**
 * 获取token
 * @param loginForm
 * @return {(function(*): Promise<void>)|*}
 */
const fetchLogin = loginForm => {
    return async dispatch => {
        const res = await loginAPI(loginForm)
        if (res.message === 'OK') {
            console.log('res = ',res)
            dispatch(setToken(res.data.token));
        }
    }
}
/**
 * 获取用户信息
 * @return {(function(*): Promise<void>)|*}
 */
const fetchUserInfo = ()=>{
    return async dispatch => {
        const res = await getProfileAPI()
        console.log(res)
        dispatch(setUserInfo(res.data))
    }
}

export {fetchLogin,fetchUserInfo,clearUserInfo}

export default userReducer